package indi.wshape1.takeawaydeliveryinfo.servlet;

import indi.wshape1.takeawaydeliveryinfo.domain.TakeOut;
import indi.wshape1.takeawaydeliveryinfo.service.UtilService;
import indi.wshape1.takeawaydeliveryinfo.util.StringUtil;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @author Wshape1
 * @create 2022-11-16 21:46
 */

@WebServlet(name = "QueryServlet", value = {"/query"})
public class QueryServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        String key = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        if (!key.equalsIgnoreCase(req.getParameter("inputVerifyCode"))) {
            writer.print("e");
            return;
        }
        String phone = req.getParameter("phone");

        String takeoutData = queryTakeout(phone);

        writer.print(takeoutData);
    }

    private String queryTakeout(String phone) {
        StringBuilder stringBuilder = new StringBuilder("[");
        if (phone != null) {
            List<TakeOut> list = UtilService.takeOutService.getListByPhone(phone);
            for (TakeOut to : list) {
                stringBuilder
                        .append("{\"name\": \"").append(to.getName())
                        .append("\", \"block\": \"").append(to.getBlock())
                        .append("\", \"group\": \"").append(to.getGroup())
                        .append("\", \"sender_phone\": \"").append(to.getSender_phone())
                        .append("\", \"time\": \"").append(to.getTimeToString())
                        .append("\", \"status\": \"").append(to.getStatus().toString())
                        .append("\", \"detail\": \"").append(StringUtil.isEmpty(to.getDetail()) ? "" : to.getDetail())
                        .append("\"},");
            }
            if (list.size() > 0)
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }

}
